package cn.td0f7.android.wangzhongcourse.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import androidx.annotation.Nullable;

public class BindService extends Service {
    private final String TAG = getClass().getName();
    private int count;// 计数
    private boolean destroy;//本服务是否注销了
    private Handler handler;

    //定义onBinder方法所返回的对象
    private MyBinder binder = new MyBinder();

    public class MyBinder extends Binder {//创建自定义的类，用于跟activity通信

        public int getCount() {//给activity提供方法
            return count;
        }

        public void setCount(int val) {
            count = val;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "onBind方法被调用!");
        return binder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate方法被调用!");
        if (handler == null) {
            handler = new Handler() {
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    count++;
                    if (!destroy) {
                        //如果没有注销每1秒执行一次
                        handler.removeMessages(1);//先清除所有没有发送的 标识为1的 消息，避免重复发送
                        handler.sendEmptyMessageDelayed(1, 1000);
                    }
                }
            };
        }
        handler.sendEmptyMessage(1);//发送一个空消息
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i(TAG, "onUnbind方法被调用!");
        return true;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.destroy = true;
        Log.i(TAG, "onDestroyed方法被调用!");
    }

    @Override
    public void onRebind(Intent intent) {
        Log.i(TAG, "onRebind方法被调用!");
        super.onRebind(intent);
    }
}